#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <cstdio>
#include "log.hpp"

class Sock
{
    const static int gbacklog = 20; // 后面再说

public:
    // const std::string & :输入性参数
    // std::string * :输出型参数
    // std::string & : 输入输出型参数
    Sock() {}
    int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0)
        {
            logMessage(FATAL, "creat sock error %d:%s", errno, strerror(errno));
            exit(1);
        }
        logMessage(NORMAL, "create sock success sock:%d", sock);
        return sock;
    }
    void Bind(int sock, uint16_t port, const std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = ip.empty() ? INADDR_ANY : inet_addr(ip.c_str());

        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind sock error %d:%s", errno, strerror(errno));
            exit(2);
        }
    }
    void Listen(int sock)
    {
        if (listen(sock, gbacklog) < 0)
        {
            logMessage(FATAL, "listen error %d:%s", errno, strerror(errno));
            exit(3);
        }
        logMessage(NORMAL, "init server success");
    }
    int Accept(int sock, std::string *ip, uint16_t *port)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        // servicesock(李四、王五等提供服务的服务员) vs _sock(张三 -- 获取新连接)
        int servicesock = accept(sock, (struct sockaddr *)&src, &len);
        if (servicesock < 0)
        {
            logMessage(ERROR, "accept error %d:%s", errno, strerror(errno));
            return -1;
        }

        if (port)
            *port = ntohs(src.sin_port);
        if (ip)
            *ip = inet_ntoa(src.sin_addr);
        return servicesock;
    }
    bool Connect(int sock, const std::string &serverip, const uint16_t &serverport)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());

        if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == 0)
            return true;

        return false;
    }

    ~Sock()
    {
    }
};